package cn.da.shuai.cool.gateway.handler;

import cn.da.shuai.cool.common.entity.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        
        R<?> errorResponse;
        if (ex instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            errorResponse = R.error(404, "Service not found");
            response.setStatusCode(HttpStatus.NOT_FOUND);
        } else {
            errorResponse = R.error(500, "Internal server error: " + ex.getMessage());
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(errorResponse));
            } catch (JsonProcessingException e) {
                return bufferFactory.wrap("{\"code\":500,\"msg\":\"JSON serialization failed\"}".getBytes());
            }
        }));
    }
}